/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package fantasy;

import java.io.IOException;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuthException;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.simpleyql.Api;
import com.simpleyql.ApiFactory;
import com.simpleyql.QueryResult;

public class StandingsServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7137643265571452101L;
	
//	private QueryResult qr;
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Properties props = new Properties();
        props.load(this.getClass().getClassLoader().getResourceAsStream("fantasy.properties"));
        
        String baseurl = props.getProperty("application.baseurl");

        // Set to expire far in the past.
		resp.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
		// Set standard HTTP/1.1 no-cache headers.
		resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		resp.setHeader("Pragma", "no-cache");

		resp.setContentType("text/plain");
		resp.getWriter().println("Testing 2 simpleyql queries");

		
		PersistenceManager pm = PMF.get().getPersistenceManager();

		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
		
		UserTable u;
		u = pm.getObjectById(UserTable.class, new String(user.getNickname()));

		Api api = ApiFactory.getApiInstance(
	            "dj0yJmk9NGVDelJyN2MzWW5zJmQ9WVdrOVRFcGFaalZrTkdrbWNHbzlNak16TVRFNE5qWXkmcz1jb25zdW1lcnNlY3JldCZ4PTM2",
	            "91b08a397dc663f4372f6a4fa31e693f6ab7bf54",
	            baseurl + "/simpleyqlcallback/",
	            false, null);

		resp.getWriter().println("Query 1:");
		
		QueryResult qr = null;
		String yql = "select * from social.profile where guid=me";
		
		try {
			qr = api.query(yql, u.getAuthdata());
		} catch (OAuthException e) {
			log("Error posting to Y!:", e);
			return;
		} catch (RuntimeException e) {
			if (e.getMessage().equals("Unable to complete the HTTP request")) {
				if (e.getCause().getMessage()
						.contains("Timeout while fetching")) {
					log("Unable to complete Yahoo! query", e);
				} else {
					log("Error posting to Y!:", e);
					return;
				}
			} else {
				throw e;
			}
		}

		// Update token, if needed (for future requests)
		if (qr != null && !qr.getAuthdata().equals(u.getAuthdata())) {
			u.setAuthdata(qr.getAuthdata());
			try {
				pm.makePersistent(u);
			} finally {
				pm.close();
			}
		}
		resp.getWriter().println(qr.getText());

		resp.getWriter().println("Query 2:");
		QueryResult qr2 = null;
		String yql2 = "select * from social.profile where guid=me";
		
		try {
			qr2 = api.query(yql2, u.getAuthdata());
		} catch (OAuthException e) {
			log("Error posting to Y!:", e);
			return;
		} catch (RuntimeException e) {
			if (e.getMessage().equals("Unable to complete the HTTP request")) {
				if (e.getCause().getMessage()
						.contains("Timeout while fetching")) {
					log("Unable to complete Yahoo! query", e);
				} else {
					log("Error posting to Y!:", e);
					return;
				}
			} else {
				throw e;
			}
		}
		
		resp.getWriter().println(qr2.getText());

	}

/*	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		resp.setContentType("text/plain");
		resp.getWriter().println("Something");
		resp.getWriter().println(this.qr.getText());
		
	}
*/	
}
